import { createRouter, createWebHistory, createWebHashHistory } from 'vue-router'
import HomeView from '../views/HomeView.vue'

const routes = [
  {
    path: '/',
    name: 'home',
    component: HomeView,
    meta: { requiresAuth: true }
  },
  {
    path: '/records',
    name: 'records',
    component: () => import('../views/RecordsView.vue'),
    meta: { requiresAuth: true }
  },
  {
    path: '/baby',
    name: 'baby',
    component: () => import('../views/BabyView.vue'),
    meta: { requiresAuth: true }
  },
  {
    path: '/complementary-food',
    name: 'complementary-food',
    component: () => import('../views/ComplementaryFoodView.vue'),
    meta: { requiresAuth: true }
  },
  {
    path: '/login',
    name: 'login',
    component: () => import('../views/LoginView.vue')
  }
]

const router = createRouter({
  history: createWebHashHistory(),
  routes
})

// 路由守卫
router.beforeEach((to, from, next) => {
  const isLoggedIn = localStorage.getItem('isLoggedIn') === 'true'
  
  // 如果需要登录但未登录，重定向到登录页
  if (to.matched.some(record => record.meta.requiresAuth) && !isLoggedIn) {
    next({ name: 'login' })
  } 
  // 如果已登录且访问登录页，重定向到首页
  else if (to.name === 'login' && isLoggedIn) {
    next({ name: 'home' })
  }
  // 其他情况正常访问
  else {
    next()
  }
})

export default router